package com.demo.datastructure.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description: letcode 15 三数之和
 * @author: ljr
 * @time: 2021/5/2 17:53
 * @since 1.2
 */
public class ThreeSumArray4 {

    public List<List<Integer>> threeSum(int[] nums) {
        int length = nums.length;
        if(length < 3){
             return new ArrayList();
        }
        List<List<Integer>> list = new ArrayList<>();
        if(length == 3){
            if(nums[0]+nums[1]+nums[2] == 0){
                List<Integer> sonList = new ArrayList<>();
                sonList.add(nums[0]);
                sonList.add(nums[1]);
                sonList.add(nums[2]);
                list.add(sonList);
                return list;
            }
            return new ArrayList();
        }

        Arrays.sort(nums);

        int newLength = length-2;
        int i = 0;
        while(i < newLength && nums[i]+nums[i+1] < 1){
            if(i != 0 && nums[i] == nums[i-1]){
                i++;
                continue;
            }


            int towIndex = i+1;
            int threeIndex = length-1;
            while(towIndex < threeIndex){
                if(nums[i]+nums[towIndex]+nums[threeIndex] == 0){
                    List<Integer> sonList = new ArrayList<>();
                    sonList.add(nums[i]);
                    sonList.add(nums[towIndex]);
                    sonList.add(nums[threeIndex]);
                    list.add(sonList);
                    towIndex++;
                    threeIndex--;
                    while(nums[towIndex] == nums[towIndex+1]){ towIndex++; }
                    while(nums[threeIndex] == nums[threeIndex-1]){ threeIndex--; }
                }else if(nums[i]+nums[towIndex]+nums[threeIndex] > 0){
                    threeIndex--;
                }else{
                    towIndex++;
                }
            }
            i++;
        }
        return list;
    }


    public static void main(String[] args) {
        ThreeSumArray4 threeSumArray = new ThreeSumArray4();
        int[] nums = new int[]{-1,0,1,2,-1,-4,-2,-3,3,0,4};
        List<List<Integer>> list= threeSumArray.threeSum(nums);
        System.out.println(list);
    }
}
